package com.spring.nio.core.event.handler;

import com.spring.nio.core.configuration.AcceptorEntity;
import com.spring.nio.core.configuration.NioServerBootstrap;
import com.spring.nio.core.event.model.EventModel;
import com.spring.nio.core.event.model.EventModelEnum;
import com.spring.nio.core.reactor.acceptor.AcceptorTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.locks.LockSupport;

/**
 * @Auther: YSFY
 * @Date: 2020-11-21 12:05
 * @Pacage_name: com.spring.nio.core.event.handler
 * @Project_Name: net-server
 * @Description: 客户端监听[AcceptorEventHandler]
 */
@Slf4j
@SuppressWarnings("all")
public class AcceptorEventHandler extends AbstractEventHandler {

    private static Map<String, AcceptorEntity> map = null;

    static {
        map = (Map<String, AcceptorEntity>) NioServerBootstrap.getConfig().getAcceptors();
    }

    @Override
    public EventModel eventHandler(EventModel eventModel) {
        if(!super.checkEventValid(eventModel)) {
            return eventModel;
        }

        if(!eventModel.getSelectionKey().isAcceptable()) {
            if(!Optional.ofNullable(super.getNextEventHandler()).isPresent()) {
                return eventModel;
            }

            return super.getNextEventHandler().eventHandler(eventModel);
        }

        return this.handler(eventModel);
    }

    /**
     * 执行处理, 唤醒对应的Acceptor线程
     * @param eventModel
     * @return eventModel
     * */
    private EventModel handler(EventModel eventModel) {
        Thread thread = null;

        if(!CollectionUtils.isEmpty(map)) {
            // 唤醒聊天Acceptor
            if(eventModel.getEventModelEnum().equals(EventModelEnum.CHAT_EVENT_ACCEPTOR)) {
                thread = map.get(AcceptorTypeEnum.CHAT_ACCEPTOR.getName()).getThread();
            }

            // 唤醒文件上传acceptor
            if(eventModel.getEventModelEnum().equals(EventModelEnum.FILE_UPLOAD_EVENT_ACCEPTOR)) {
                thread = map.get(AcceptorTypeEnum.FILE_UPLOAD_ACCEPTOR.getName()).getThread();
            }

            // 唤醒文件下载acceptor
            if(eventModel.getEventModelEnum().equals(EventModelEnum.FILE_DOWNLOAD_EVENT_ACCEPTOR)) {
                thread = map.get(AcceptorTypeEnum.FILE_DOWNLOAD_ACCEPTOR.getName()).getThread();
            }
        }

        if(Optional.ofNullable(thread).isPresent()) {
            LockSupport.unpark(thread);
        }

        return eventModel;
    }
}
